#!/bin/bash

# source ~/.config/scripts/fzf-sshscp/servers.sh
DIR_CONFIG="$HOME/.config/scripts/fzf-sshscp"
# set -a
# DIR_CONFIG=$(dirname `readlink --canonicalize "${BASH_SOURCE[0]}"`)
# readonly DIR_CONFIG="$HOME/.config/scripts/fzf-sshscp/"
# source ~/.config/scripts/fzf-sshscp/servers.sh
# source "$PROJECT_ROOT/servers.sh"
source "$DIR_CONFIG/servers.sh"

_preview() {
    index=$(_index "$1")
    echo ${sshcmds[index]} ${targets[index]}
}

_cmdstr() {
    index=$(_index "$1")
    echo ${sshcmds[index]} ${targets[index]}
}

_copytext() {
    index=$(_index "$1")
    echo -n ${copytext[index]}
}

_ssh() {
    # linux
    # server=$(_list | fzf \
    #     --cycle \
    #     --header='请选择服务器(tab复制地址)' \
    #     --header-first \
    #     --bind='tab:execute(h=$(~/.config/scripts/fzf-sshscp/ssh.sh copytext {}) && lemonade copy $h && echo $h copied)+abort' \
    #     --preview="~/.config/scripts/fzf-sshscp/ssh.sh preview {}" \
    #     --height=10 \
    #     --preview-window=bottom:1:wrap
    # )
    # macOS
    server=$(_list | fzf \
        --cycle \
        --header='请选择服务器(tab复制)' \
        --header-first \
        --bind='tab:execute(h=$(~/.config/scripts/fzf-sshscp/ssh.sh cmdstr {}) && echo $h | pbcopy)+abort' \
        --preview="~/.config/scripts/fzf-sshscp/ssh.sh preview {}" \
        --height=81% \
        --preview-window=bottom:1:wrap
    )

    [[ -z "$server" ]] && exit 0
    [[ -z "$(_index "$server")" ]] && echo $server && exit 0
    # [[ -z "$(_copytext "$server")" ]] && echo $server && exit 0
    # 复制密码到剪贴板
    # echo -e "copy $(_copytext "$server") ..."
    # echo -e "copy passwd  ..."
    echo -e "copy "$server" passwd  ..."
    echo -e "$(_copytext "$server")" | pbcopy  
    echo -e "copy success."

    # 执行连接命令
    echo -e "$(_preview "$server")\nconnecting..."
    exec $(_preview "$server")

}

case $1 in
    "") _ssh ;;
    preview) _preview "$2" ;;
    copytext) _copytext "$2" ;;
    cmdstr) _cmdstr "$2" ;;
    *) ssh $* ;;
esac
